// pages/login-code/login-code.js
import request from '../../../../utils/request';
// app实例
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    phone: '',
    serectPhone: '',
    code: '',
    time: 60,
    isSendCode: true,
    maxLength: 4
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const phone = options.phone
    this.setData({
      phone,
      serectPhone: phone.slice(0, 3) + '****' + phone.slice(7)
    })
  },

  goLoginPhone() {
    wx.redirectTo({
      url: `../login-phone/login-phone?phone=${this.data.phone}`,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this._setCountDown()
  },
  // 设置倒计时
  _setCountDown() {
    this.timeId = setInterval(() => {
      const time = this.data.time - 1;
      if (time <= 0) {
        clearInterval(this.timeId);
        this.setData({
          isSendCode: false
        })
        return
      }
      this.setData({
        time
      })
    }, 1000);
  },

  async sendCode() {
    if (this.data.isSendCode) {
      return;
    }
    // 重新发送验证码
    await request('/captcha/sent', {
      phone: this.data.phone
    })

    this.setData({
      isSendCode: true,
      time: 60,
    })

    this._setCountDown();
  },
  // 注意：input事件回调函数不能是async函数
  handleInput(e) {
    const code = e.detail.value;
    this.setData({
      code
    })
    if (code.length === this.data.maxLength) {
      this._verifyCode();
    }
  },

  async _verifyCode() {
    const { phone, code: captcha } = this.data;
    // 验证验证码是否正确
    await request('/captcha/verify', {
      phone,
      captcha
    });
    // 登录
    const res = await request('/login/cellphone', {
      phone,
      captcha
    });
    // cookie: ''
    // profile: { userId, nickname, avatarUrl }
    // 存储在全局 app.globalData,所有组件访问
    const profile = {
      userId: res.profile.userId, 
      nickname: res.profile.nickname, 
      avatarUrl: res.profile.avatarUrl,
    }
    const cookie = `MUSIC_U=${res.token}`;
    app.globalData.profile = profile;
    app.globalData.cookie = cookie;
    // 存储本地 storage
    wx.setStorageSync('cookie', cookie)
    wx.setStorageSync('profile', JSON.stringify(profile));
    
    wx.switchTab({
      url: '/pages/my/my',
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    clearInterval(this.timeId);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    clearInterval(this.timeId);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})